package com.docios.cookbook2.ui.otherPager;

import static androidx.core.text.HtmlCompat.FROM_HTML_MODE_COMPACT;
import static androidx.core.text.HtmlCompat.FROM_HTML_MODE_LEGACY;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.menu.ActionMenuItemView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.docios.cookbook2.Dao.AppDatabase;
import com.docios.cookbook2.Dao.DatabaseImpl;
import com.docios.cookbook2.Dao.QueryBeanDao;
import com.docios.cookbook2.R;
import com.docios.cookbook2.databinding.ActivityDetailBinding;
import com.docios.cookbook2.entity.MaterialBean;
import com.docios.cookbook2.entity.ProcessBean;
import com.docios.cookbook2.entity.QueryBean;
import com.docios.cookbook2.utils.TagDivider;

import java.util.ArrayList;
import java.util.List;

public class QueryDetailActivity extends AppCompatActivity {

    QueryBeanDao queryBeanDao;
    QueryBean bean = null;
    List<MaterialBean> materialBeans = null;
    List<ProcessBean> processBeans = null;
    String tagString = "";

    boolean isFavorite = false;

    ActivityDetailBinding detailBinding;

    @SuppressLint("NonConstantResourceId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        detailBinding = ActivityDetailBinding.inflate(getLayoutInflater());
        setContentView(detailBinding.getRoot());

        initData();
        initView();
        detailBinding.topBar.setNavigationOnClickListener(f -> finish());
        topMenuOnClick();

    }

    private void initData() {
        //实例化数据库
        AppDatabase db = DatabaseImpl.setInstance(getApplicationContext());
        queryBeanDao = db.queryBeanDao();

        //接收intent传来的raw数据
        bean = (QueryBean) getIntent().getSerializableExtra("data");

        //分类存入
        assert bean != null;
        materialBeans = new ArrayList<>(bean.getMaterialBeans());
        processBeans = new ArrayList<>(bean.getProcessBeans());
        tagString = bean.getTag();

    }

    @SuppressLint("SetTextI18n")
    private void initView() {
        //收藏按钮切换
        changeStarView();
        //页首文本
        runOnUiThread(() -> {
            //页首标题
            detailBinding.detailTitle.setTitle(bean.getName());
            /*
             * html格式文本处理
             * FROM_HTML_MODE_LEGACY：div换行2倍行距
             * */
            String htmlContent = bean.getContent();
            CharSequence styledText = Html.fromHtml(htmlContent, FROM_HTML_MODE_LEGACY);
            detailBinding.content.setText(styledText);
            //小贴士
            detailBinding.peopleNum.setText(bean.getPeoplenum());
            detailBinding.cookingTime.setText(bean.getCookingtime());
        });
        //页首大图
        runOnUiThread(() -> {
                    RequestOptions requestOptions = new RequestOptions()
                            .placeholder(R.drawable.food_picture_null)
                            .error(R.drawable.food_picture_null)
                            .fallback(R.drawable.food_picture_null);
                    Glide.with(this)
                            .load(bean.getPic())
                            .apply(requestOptions)
                            .into(detailBinding.detailImgHeader);
                }
        );
        //标签
        runOnUiThread(() -> {
            //分好的标签
            List<String> tagWords = new TagDivider().tagDivider(tagString);
            // 设置tag文本
            for (String tagWord : tagWords) {
                @SuppressLint("InflateParams") View tagLayout = LayoutInflater.from(this).inflate(R.layout.item_detail_tags, null);
                Button tag = (Button) tagLayout.findViewById(R.id.item_tags);
                tag.setText(tagWord);
                //加入子view
                detailBinding.flexbox.addView(tagLayout);
            }
        });
        //原料
        runOnUiThread(() -> {
            for (MaterialBean materialBean : materialBeans) {
                //设置原料名字
                @SuppressLint("InflateParams") View materialLayout = LayoutInflater.from(this).inflate(R.layout.item_detail_material, null);
                TextView materialText = (TextView) materialLayout.findViewById(R.id.detail_material_text);
                materialText.setText(materialBean.getMname());
                //原料用量
                TextView doseText = (TextView) materialLayout.findViewById(R.id.detail_dose_text);
                doseText.setText(materialBean.getAmount());
                //加入子view
                detailBinding.detailMaterial.addView(materialLayout);
            }
        });
        //步骤
        runOnUiThread(() -> {
            for (int i = 0; i < processBeans.size(); i++) {
                //给步骤标序号
                @SuppressLint("InflateParams") View processLayout = LayoutInflater.from(this).inflate(R.layout.item_detail_process, null);
                TextView processNum = (TextView) processLayout.findViewById(R.id.process_detail_num);
                processNum.setText("步骤 " + (i + 1));
                //步骤图片
                ImageView processImg = (ImageView) processLayout.findViewById(R.id.process_detail_img);
                RequestOptions requestOptions = new RequestOptions()
                        .placeholder(R.drawable.food_picture_null)
                        .error(R.drawable.food_picture_null)
                        .fallback(R.drawable.food_picture_null);
                Glide.with(this)
                        .load(processBeans.get(i).getPic())
                        .apply(requestOptions)
                        .into(processImg);
                //步骤描述
                TextView pContent = (TextView) processLayout.findViewById(R.id.process_detail_content);
                String rawContent = processBeans.get(i).getPcontent();
                CharSequence styledPContent = Html.fromHtml(rawContent, FROM_HTML_MODE_COMPACT);
                pContent.setText(styledPContent);
                //添加子view
                detailBinding.processDetail.addView(processLayout);
            }
        });


    }

    private void topMenuOnClick() {
        detailBinding.topBar.setOnMenuItemClickListener(menuItem -> {
            switch (menuItem.getItemId()) {
                case R.id.menu_detail_favorite:
                    if (isFavorite) {
                        queryBeanDao.deleteQ(bean);
                        Toast.makeText(this, "取消收藏", Toast.LENGTH_SHORT).show();
                    } else {
                        queryBeanDao.insertQ(bean);
                        Toast.makeText(this, "已收藏", Toast.LENGTH_SHORT).show();
                    }
                    isFavorite = !isFavorite;
                    //收藏按钮切换
                    changeStarView();
                    break;
                case R.id.menu_detail_thumb:
                    Toast.makeText(this, "赞", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.menu_detail_share:
                    Toast.makeText(this, "分享", Toast.LENGTH_SHORT).show();
                    break;
            }
            return false;
        });
    }


    /*
     * 收藏按钮切换
     * */
    private void changeStarView() {
        runOnUiThread(() -> {
            List<QueryBean> favoriteBeans = queryBeanDao.getAllByIdQ(bean.getId());
            isFavorite = favoriteBeans.size() > 0;

            ActionMenuItemView favoriteItemView = (ActionMenuItemView) detailBinding.topBar.findViewById(R.id.menu_detail_favorite);
            @SuppressLint("RestrictedApi") MenuItem favoriteItem = favoriteItemView.getItemData();
            favoriteItem.setIcon(isFavorite ? R.drawable.star_fill_24 : R.drawable.star_outline_24);
        });
    }




}